<!-- 
 * howcode-chat 客服聊天功能
 * Copyright (c) 2021 howcode https://gitee.com/howcode All rights reserved.
 * 复制使用请保留本段注释，感谢支持开源！
 * 
 * 
 * 
 -->
<template>
	<view>
		<view class="chatBox">
			<scroll-view id="ChatContent" scroll-y class="chatContent" :style="{height:chatContentHeight + 'px'}"
				:scroll-top="scrollTop">
				<view v-if="lastSession">
					<view class="moreSession" v-on:click.stop="loadMore">加载更多</view>
				</view>
				<view v-else :key="index">
					<view class="moreSession">已加载全部</view>
				</view>
				<view v-for="(item, index) in conversition">
					<view :key="index" v-if="item.SendId == sender.id && item.Identity == 2">
						<view class="myself_item">
							<view v-if="item.State == 0">
								<!-- <van-loading v-if="item.Type == 1" type="spinner" class="myselfImageLoad" size="24px">
								</van-loading>
								<van-loading v-else :key="index" type="spinner" class="myselfLoad" size="24px">
								</van-loading> -->
							</view>
							<view v-else-if="item.State == -1">
								<text v-if="item.Type == 1" class="sendImageError">!</text>
								<text :key="index" v-else class="sendError">!</text>
							</view>
							<view v-if="item.Type == 0" class="myselfContent">
								{{ item.Content }}
							</view>
							<view v-else-if="item.Type == 2" class="myselfContent">
								<image class="expression_img" mode="widthFix" v-bind:src="item.Content" />
							</view>
							<image v-else-if="item.Type == 1" class="mineSendImage" @tap="previewImg" :data-imgurl="item.Content" preview="1"
								v-bind:src="item.Content" mode="widthFix"/>
							<view v-else-if="item.Type == 3" class="myOtherContent">
								<view class="goods-wrap">
									<view class="goods-thum">
										<image :src="item.Thumbnail" mode="widthFix" />
									</view>
									<view class="goods-detail">
										<p class="goods-title" :title="item.Title">
											{{ item.Title }}
										</p>
										<p class="goods-abstract" :title="item.Description">
											{{ item.Description }}
										</p>
										<p class="goods-label" :title="item.Label">
											<text class="rmb-icon"></text>{{ item.Label }}
										</p>
									</view>
								</view>
								<view v-if="item.noSend" class="sendCard" v-on:click.stop.stop="sendCard(item)">
									发给客服
								</view>
								<view v-else-if="item.noSend == false" class="sendCard" style="background: #eee">
									已发送
								</view>
							</view>
							<!-- #ifdef MP-WEIXIN -->
							<open-data class="myselfImage" type="userAvatarUrl"
								default-avatar="https://dev.stall.lkxlkf.com/ca/icons/default/default-icon.png">
							</open-data>
							<!-- #endif -->
							<!-- #ifdef H5 -->
							<view class="myselfImage">
								<image :src="customerImg" mode="widthFix"></image>
							</view>
							<!-- #endif -->
						</view>
						<view style="clear: both"></view>
					</view>
					<view :key="index" v-else-if="item.Identity == 1">
						<view class="customerServiceBlock">
							<view class="customerServiceImage">
								<image v-bind:src="serviceImg" mode="widthFix" />
							</view>
							<view v-if="item.Type == 0" class="otherContent" v-html="item.Content"></view>
							<view v-else-if="item.Type == 2" class="otherContent">
								<image v-bind:src="item.Content" mode="widthFix"/>
							</view>
							<image v-else-if="item.Type == 1" class="yourSendImage" v-bind:src="item.Content"
								@tap="previewImg" :data-imgurl="item.Content" preview="1" mode="widthFix"/>
							<view v-else-if="item.Type == 3" class="otherContent" style="padding: 0.1rem">
								<a :href="item.Content" target="_blank">
									<view class="goods-wrap">
										<view class="goods-thum">
											<image :src="item.Thumbnail" mode="widthFix" />
										</view>
										<view class="goods-detail">
											<p class="goods-title" :title="item.Title">
												{{ item.Title }}
											</p>
											<p class="goods-abstract" :title="item.Description">
												{{ item.Description }}
											</p>
											<p class="goods-label" :title="item.Label">
												<text class="rmb-icon"></text>{{ item.Label }}
											</p>
										</view>
									</view>
								</a>
							</view>
							<view v-else-if="
			                    item.Type == '4' &&
			                    item.Content.IsParent &&
			                    item.Content.ReplyLink
			                  " class="otherContent">
								<p>{{ item.Content.Reply }}</p>
								<view v-for="(link, index2) in item.Content.ReplyLink" :key="index2"
									style="color: #da2339; padding: 5px 0"
									v-on:click.stop="linkReply(link.Answer, link.Reply)">
									{{ index2 + 1 }}.{{ link.Answer }}
								</view>
							</view>
							<view v-else-if="item.Type == '4'" v-html="item.Content.Reply" class="otherContent"></view>
						</view>
						<view style="clear: both"></view>
					</view>
					<view :key="index" v-else-if="item.Identity == 3">
						<view class="otherBlock">
							<text>{{ item.Content }}</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!--底部浮动内容-->
		<view id="floatBottom" class="floatBlock">
			<view class="inputBox">
				<view v-show="!sender.onlineState" id="toPeopleService" class="robotServices"
					v-on:click.stop="callPeople">
					<image src="../../static/img/service/客服.png" />
					<view class="robotFont">转人工</view>
				</view>
				<view :class="!sender.onlineState ? 'inputBlock' : 'inputBlock2'">
					<input class="inputContent" type="text" v-model="sendInfo" v-on:focus="openMore('input')" />
				</view>
				<view class="bottom_right" v-show="!sender.onlineState">
					<view v-show="sendInfo.length > 0" class="sendToRobot" v-on:click.stop="sendToRobot">发送</view>
					<view v-show="sendInfo.length <= 0">
						<view class="openMore" v-on:click.stop="openMore('tool')">
							<image src="../../static/img/service/加号.png" mode="widthFix" />
						</view>
					</view>
				</view>
				<view v-if="sender.onlineState" style="flex: 2;display: flex;">
					<view class="sendExpression" v-on:click.stop="openMore('expression')">
						<image src="../../static/img/service/笑脸.png" mode="widthFix" />
					</view>
					<view v-show="sendInfo.length > 0" style="flex: 1;">
						<view class="sendToPeople" v-on:click.stop="toSend(sendInfo, 2, 0)">
							发送
						</view>
					</view>
					<view v-show="sendInfo.length <= 0" class="openMore" v-on:click.stop="openMore('tool')">
						<image src="../../static/img/service/加号.png" mode="widthFix" />
					</view>
				</view>
			</view>
			<section v-if="moreTool && sender.onlineState" class="moreTool">
				<ul class="toolUl">
					<template v-for="(item, index) in toolBox">
						<li :key="index">
							<view class="item" v-on:click.stop="index == 1 ? (showComment = true) : ''">
								<view class="toolIcon">
									<image class="toolImage" mode="heightFix" v-bind:src="item.image" />
									<input v-if="index == 0" class="FileImage" name="customer" type="file" value=""
										v-on:click="uploadImage" />
								</view>
							</view>
							<text class="totalName">{{ item.name }}</text>
						</li>
					</template>
				</ul>
			</section>
			<section v-else-if="moreTool && !sender.onlineState" class="moreTool" style="height: 150rpx">
				<ul class="toolUl">
					<template v-for="(item, index) in robotToolBox">
						<li :key="index">
							<view class="item" v-on:click.stop="showMessage = true">
								<view class="toolIcon">
									<image class="toolImage" mode="heightFix" v-bind:src="item.image" />
								</view>
							</view>
							<text class="totalName">{{ item.name }}</text>
						</li>
					</template>
				</ul>
			</section>
			<view v-show="expressionShow" class="expressionShow">
				<view class="face">
					<ul>
						<template v-for="(item, index) in expressions">
							<li :key="index">
								<image class="customerSendExpression" v-bind:src="item.image" v-bind:title="item.title"
									v-on:click.stop="toSend(item.image, 2, 2)" mode="widthFix" />
							</li>
						</template>
					</ul>
				</view>
			</view>
			<eject-drawer mode="bottom" :visible="showComment" @close="showComment = false" drawerWidth="100%"
				drawerHeight="50%">
				<view class="showComment">
					<view class="commentTitle" style="display: block">
						请对本次服务进行评价
					</view>
					<view class="commentStart">
						<template v-for="(item, index) in start">
							<view :key="index" class="startImage">
								<image v-if="!item.state" v-bind:src="item.offstart"
									v-on:click.stop="changeLevel(item, index)" />
								<image v-else v-bind:src="item.onstart" v-on:click.stop="changeLevel(item, index)" />
							</view>
						</template>
					</view>
					<view class="isSolve">
						<view>{{ thisQuestion }}</view>
						<template v-for="(item, index) in solveState">
							<button :key="index" class="tablSelect" v-bind:class="{ activeSelect: item.state }"
								v-on:click.stop="onClickSelect(index)">
								{{ item.name }}
							</button>
						</template>
					</view>
					<view class="submitBlock">
						<view class="submitBtn" v-bind:class="{ activeBtn: level > 0 && solveResult != -1 }"
							v-on:click.stop="sumbitComment">
							提交
						</view>
					</view>
				</view>
			</eject-drawer>
			<eject-drawer mode="bottom" :visible="showMessage" @close="showMessage = false" drawerWidth="100%"
				drawerHeight="60%">
				<view class="showMessage">
					<view class="commentTitle">
						<text v-bind:class="{ messageActive: messageType }" class="messageTopBtn"
							v-on:click.stop="changeMessageType(true)">请您留言</text>
						<text v-bind:class="{ messageActive: !messageType }" class="messageTopBtn"
							v-on:click.stop="changeMessageType(false)">留言记录</text>
					</view>
					<view v-show="messageType">
						<view class="messageTip">
							{{ messageTip }}
						</view>
						<textarea v-model="customerMessage" :placeholder="messageTip2" maxlength="200" id="remark"
							class="textarea_box"></textarea>
						<view class="submitBlock" style="margin-top: 0.5rem">
							<view class="submitBtn" v-bind:class="{ activeBtn: customerMessage.length > 0 }"
								v-on:click.stop="sumbitMessage">
								提交
							</view>
						</view>
					</view>
					<view v-show="!messageType" class="messageRecord">
						<view v-for="(item, index) in messageList" :key="index" class="messageBlock">
							<view class="messageTime">{{ item.CreateTime }}</view>
							<view class="messageContent">
								<view class="messageDetail">{{ item.Message }}</view>
								<view class="messageState" v-if="item.State == 0">待回复</view>
								<view class="messageState" v-else-if="item.State == 4" v-on:click.stop="item.State = 3">
									∧收起
								</view>
								<view class="messageState" style="background: #da2339" v-else
									v-on:click.stop="seeMessageDetail(item)">
									查看详情
								</view>
							</view>
							<view v-if="item.State == 4" style="text-align: left">
								<view>客服：{{ item.SolverName }}</view>
								<view>{{ item.Reply }}</view>
							</view>
						</view>
					</view>
				</view>
			</eject-drawer>
			<w-compress ref='wCompress' />
		</view>
	</view>
</template>
<script>
	import Common from "../../static/js/common.js"
	import Config from "../../static/js/config.js"
	import ejectDrawer from "../eject-drawer/eject-drawer.vue"
	import WCompress from '../common/w-compress.vue'
	import io from "../../static/jdk/socket.io.js";
	import fastReply from "../../static/json/fastReply.json";
	import messageList from "../../static/json/messageList.json";
	import productList from "../../static/json/product.json";
	import robotReply from "../../static/json/robotReply.json";
	import userList from "../../static/json/userList.json";
	let that = null

	const socket = io('http://localhost:3100', {
		query: {},
		transports: ['websocket', 'polling'],
		timeout: 5000,
	});

	socket.on('connect', () => {
		// 接收机器人回复的信息
		socket.on("reviceFromRobot", (data) => {
			if (data.flag) {
				that.signalrService(data.content, 1, 4, false);
			} else {
				that.signalrService(data.content, 1, 0, false);
			}
		});
		// 加入会话成功
		socket.on("joinSuccess", (data) => {
			uni.hideLoading()
		});
		//当前用户接收加入提示信息
		socket.on("joinTip", (data) => {
			that.sender.onlineState = true;
			that.revicer.id = data.ReviceId;
			that.revicer.name = data.ReviceName;
			that.revicer.outTradeNo = data.ReviceOutTradeNo;
			that.infoTemplate = {
				SendId: 0,
				ReviceId: 0,
				Content: "客服" + data.ReviceName + "为您服务",
				Identity: 3,
				Type: 0,
				State: 1,
				NoCode: null,
				CreateDateUtc: null,
				Title: null,
				Description: null,
				Label: null,
				Thumbnail: null,
				NoSend: true,
			};
			that.toSendInfo(that.infoTemplate);
			if (that.browseCard.Id > 0) {
				that.infoTemplate = {
					SendId: that.sender.id,
					ReviceId: that.revicer.id,
					Content: "" + that.browseCard.Id,
					Identity: 2,
					Type: 3,
					State: 1,
					OutTradeNo: that.revicer.outTradeNo,
					NoCode: +new Date(),
					CreateDateUtc: null,
					Title: that.browseCard.Name,
					Description: that.browseCard.ShortDescription,
					Label: that.browseCard.Amount,
					Thumbnail: that.browseCard.DefaultPictureUrl,
					NoSend: true,
				};
				that.toSendInfo(that.infoTemplate);
			}
			that.toBottom(100);
		});
		//当前用户接收加入失败提示
		socket.on("joinError", (data) => {
			that.infoTemplate = {
				SendId: 0,
				ReviceId: 0,
				Content: data.msg,
				Identity: 3,
				Type: 0,
				State: 1,
				NoCode: null,
				OutTradeNo: null,
				CreateDateUtc: null,
				Title: null,
				Description: null,
				Label: null,
				Thumbnail: null,
				NoSend: true,
			};
			that.toSendInfo(that.infoTemplate);
			that.toBottom(100);
			uni.hideLoading()
		});
		//当前用户接收对方离线提示
		socket.on("offLineTip", (data) => {
			that.showMsg(data.msg);
			that.conversition.forEach((x) => {
				if (x.SendId == that.sender.id) {
					x.State = -1;
					that.sendState = true;
				}
			});
		});
		//修改信息状态
		socket.on("changOrShowMsg", (data) => {
			that.sendState = true;
			clearTimeout(that.msgTimer);
			that.conversition.forEach((x) => {
				if (x.NoCode != null && x.NoCode == data.NoCode) {
					x.State = 1;
				}
			});
		});
		//接收信息
		socket.on("reviceMsg", (data) => {
			if(that.sender.onlineState)
				that.toSendInfo(data);
		});
		//客服离线成功
		socket.on("offSuccess", (data) => {
			uni.hideLoading()
			if (
				!that.sender.isService &&
				that.sender.onlineState &&
				that.revicer.id == data.SendId
			) {
				that.infoTemplate = {
					SendId: 0,
					ReviceId: 0,
					Content: "当前客服已离线",
					Identity: 3,
					Type: 0,
					State: 1,
					NoCode: null,
					OutTradeNo: null,
					CreateDateUtc: null,
					Title: null,
					Description: null,
					Label: null,
					Thumbnail: null,
					NoSend: true,
				};
				that.toSendInfo(that.infoTemplate);
				that.sender.onlineState = false;
			}
		});
		//客服主动关闭会话
		socket.on("closeSessionSuccess", (data) => {
			if (!that.sender.isService) {
				that.infoTemplate = {
					SendId: 0,
					ReviceId: 0,
					Content: "客服结束了本次会话",
					Identity: 3,
					Type: 0,
					State: 1,
					NoCode: null,
					OutTradeNo: null,
					CreateDateUtc: null,
					Title: null,
					Description: null,
					Label: null,
					Thumbnail: null,
					NoSend: true,
				};
				that.toSendInfo(that.infoTemplate);
				that.sender.onlineState = false;
			}
		});
		//客服刷新或关闭离线
		socket.on("serviceDisconnect", (data) => {
			if (that.sender.onlineState) {
				that.infoTemplate = {
					SendId: 0,
					ReviceId: 0,
					Content: "当前客服已下线",
					Identity: 3,
					Type: 0,
					State: 1,
					NoCode: null,
					OutTradeNo: null,
					CreateDateUtc: null,
					Title: null,
					Description: null,
					Label: null,
					Thumbnail: null,
					NoSend: true,
				};
				that.toSendInfo(that.infoTemplate);
				that.sender.onlineState = false;
			}
		});
		//多设备在线时，强制旧设备下线
		socket.on("squeezeOut", (data) => {
			if (that.noCode === data.noCode) {
				if (!that.sender.isService) {
					that.signalrService("账户已在其他设备登陆，会话中断", 3, 0, false);
					that.sender.onlineState = false;
				}
			}
		});
	});

	export default {
		components: {
			ejectDrawer,
			WCompress
		},
		data() {
			return {
				socket: null,
				windowHeight: 0,
				chatContentHeight: 0,
				floatBottomHeight: 0,
				scrollTop: 0,
				sender: {
					id: 3,
					isService: 0,
					name: "",
					onlineState: false,
					outTradeNo: "",
					source: "",
					mobile: "",
					nickName: "",
					cardNo: "",
					receptNum: 0,
				},
				revicer: {
					id: 0,
					isService: 0,
					name: "",
					outTradeNo: "",
					source: "",
					mobile: "",
					nickName: "",
					cardNo: "",
					receptNum: 0,
				},
				infoTemplate: {},
				level: 0,
				solveResult: -1,
				pageIndex: 1,
				current_state: 1,
				pageSize: 10,
				sendInfo: "",
				customerMessage: "",
				thisQuestion: "本次问题：",
				imageList:[],
				customerImg: require("../../static/img/service/customerImg.png"),
				serviceImg: require("../../static/img/service/serviceImg.png"),
				messageTip: "您好，很抱歉我们暂时无法为您提供服务，如需帮助，请留言，我们将尽快联系并解决您的问题",
				messageTip2: "您好，为了更好地解决您的问题，请尽可能地描述清楚问题(最多200字)",
				noCode: +new Date(),
				msgTimer: null,
				moreTool: false,
				isSelectSession: false,
				expressionShow: false,
				showComment: false,
				showMessage: false,
				lastSession: true,
				sendState: true,
				messageType: true,
				conversition: [],
				messageList: [],
				toolBox: Config.TOOLBOX,
				robotToolBox: Config.ROBOTTOOLBOX,
				expressions: Config.EXPRESSIONS,
				start: Config.STARTLIST,
				solveState: Config.SOLVESTATE,
				browseCard: {
					Id: 0,
					Name: "",
					ShortDescription: "",
					DefaultPictureUrl: "",
					Amount: 0,
					Type: 0,
				},
				openImitateProduct:true
			};
		},
		methods: {
			//初始化
			init() {
				if(this.openImitateProduct){
					let product = productList.filter(
						(x) => x.Id == 300
					);
					if (product.length > 0) {
						this.browseCard.Id = product[0].Id;
						this.browseCard.Name = product[0].Name;
						this.browseCard.ShortDescription = product[0].ShortDescription;
						this.browseCard.DefaultPictureUrl = product[0].DefaultPictureUrl;
						this.browseCard.Amount = "编码:" + product[0].ProductCode;
						this.browseCard.Type = 1;
					}
				}
				let userInfo = userList.filter(
					(x) => x.id == this.sender.id
				)[0];
				if (userInfo) {
					this.sender.name = userInfo.name;
					this.sender.isService = userInfo.isService;
					this.sender.receptNum = userInfo.receptNum;
				} else {
					alert("请保证sendId参数在userList.json文件中存在");
					return false;
				}
				//发送欢迎语
				let welCome = robotReply.filter(
					(x) => x.Answer.indexOf("欢迎语") !== -1
				);
				if (welCome.length > 0) {
					this.signalrService(welCome[0], 1, 4, false);
				}
			},
			//获取设备信息
			async getTelephoneInfo() {
				uni.getSystemInfo({
					success: (res) => {
						this.windowHeight = res.windowHeight
						let info = uni.createSelectorQuery().in(this).select("#floatBottom");
						info.boundingClientRect((data) => { //data - 各种参数
							this.floatBottomHeight = data.height
							this.chatContentHeight = res.windowHeight - data.height
						}).exec()
					}
				})
			},
			//查看大图
			previewImg(e){
				let imgArr = [];
				for (let i = 0; i < this.conversition.length; i++) {
					if (this.conversition[i].Type === 1) {
						imgArr.push(this.conversition[i].Content)
					}
				}
				let index = 0;
				for (let i = 0; i < imgArr.length; i++) {
					if (imgArr[i] == e.currentTarget.dataset.imgurl) {
						index = i;
						break;
					}
				}
				uni.previewImage({
					current: index,
					urls: imgArr
				})
			},
			//会员发送卡片给客服
			sendCard(item) {
				if (item.noSend) {
					item.noSend = !item.noSend;
					item.merchantKey = this.sender.merchantKey
					this.sendMsg(item)
				} else {
					this.showMsg("已发送");
				}
			},
			//上传图片
			uploadImage() {
				let _this = this;
				let identity = this.sender.isService ? 1 : 2;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						let type = "jpg";
						let rate = "0.8";
						if (res.tempFiles[0].path.indexOf("png") >= 0) {
							type = "png"
						} else if (res.tempFiles[0].path.indexOf("jpeg") >= 0) {
							type = "jpeg"
						}
						if (res.tempFiles[0].size < 1024000) {
							rate = "0.9"
						} else if (res.tempFiles[0].size > 1024000 && res.tempFiles[0].size <= 2048000) {
							rate = "0.8"
						} else if (res.tempFiles[0].size > 2048000 && res.tempFiles[0].size <= 5120000) {
							rate = "0.5"
						} else if (res.tempFiles[0].size > 5120000 && res.tempFiles[0].size < 10240000) {
							rate = "0.4"
						} else if (res.tempFiles[0].size > 10240000) {
							this.$Common.tipMsg("图片大小不得超过10M")
							return;
						}
						uni.showLoading({
							title: '上传图片中...',
							mask: true
						})
						this.$refs.wCompress.start(res.tempFilePaths[0], {
								pixels: 4000000, // 最大分辨率，默认二百万
								quality: rate, // 压缩质量，默认0.8
								type: type, // 图片类型，默认jpg
								base64: false, // 是否返回base64，默认false，非H5有效
							})
							.then(res => {
								/**base64转换，临时查看图片*/
								uni.getFileSystemManager().readFile({
									filePath:res,
									encoding:'base64',
									success:r=>{
										let url = "data:image/jpeg;base64," + r.data
										this.imageList.push(url);
										uni.hideLoading();
										this.signalrService(url, identity, 1);
									}
								})
								/**生产环境，上传服务器*/
								// wx.uploadFile({
								// 	url: '服务器接口', //此处换上你的接口地址
								// 	filePath: res,
								// 	name: res,
								// 	header: {
								// 		"Content-Type": "multipart/form-data",
								// 		'accept': 'application/json'
								// 	},
								// 	formData: {},
								// 	success: (res) => {
								// 		uni.hideLoading();
								// 		this.imageList.push(res.url);
								// 		this.signalrService(url, identity, 1);
								// 	},
								// 	fail: function(res) {
								// 		console.log('fail');
								// 	},
								// })
							})
							.catch(e => {
								uni.hideLoading()
							})
					}
				});
			},
			//点击机器人链接
			linkReply(answer, reply) {
				this.signalrService(answer, 2, 0, false, true);
				this.signalrService(reply, 1, 0, false, true);
				this.toBottom(100);
			},
			//发送消息给会员或客服
			toSend(content, identity, type) {
				if (type === 0 && content.length <= 0) {
					Common.tipMsg("请输入发送内容");
					return;
				}
				if (type === 2 && this.sender.isService) {
					this.expressionShow = !this.expressionShow;
				}
				this.signalrService(content, identity, type);
			},
			//改变评分
			changeLevel(item, index) {
				for (var i = 0; i < this.start.length; i++) {
					if (i <= index) {
						this.start[i].state = true;
					} else {
						this.start[i].state = false;
					}
				}
				this.level = item.level;
			},
			//已解决或未解决
			onClickSelect(index) {
				for (var i = 0; i < this.solveState.length; i++) {
					this.solveState[i].state = false;
				}
				this.solveState[index].state = !this.solveState[index].state;
				this.solveResult = this.solveState[index].value;
			},
			//提交评价
			sumbitComment() {
				uni.showLoading()
				/*
				 * ##发起请求提交评价
				 */
				this.showComment = false;
				Common.tipMsg("发起请求提交评价");
			},
			//呼叫客服
			callPeople() {
				uni.showLoading();
				this.joinChat();
			},
			//加入会话
			joinChat() {
				socket.emit("joinChat", {
					SendId: this.sender.id,
					ReviceId: this.revicer.id,
					SendName: this.sender.name,
					ReviceName: this.revicer.name,
					IsService: this.sender.isService,
					NoCode: this.noCode,
				});
			},
			//留言与留言记录的切换
			changeMessageType(flat) {
				this.messageType = flat;
				if (!flat) {
					/*
					 * ##发起请求获取留言信息
					 */
					Common.tipMsg("发起请求获取留言信息");
					// this.messageList = this.$store.state.messageList;
				}
			},
			//机器人聊天
			sendToRobot() {
				if (this.sendInfo != "") {
					let createDate = this.nowTime();
					let noCode = +new Date();
					let content = this.sendInfo;
					this.sendInfo = "";
					this.infoTemplate = {
						SendId: this.sender.id,
						ReviceId: 0,
						Content: content,
						Identity: 2,
						Type: 0,
						State: 0,
						NoCode: noCode,
						OutTradeNo: null,
						CreateDateUtc: createDate,
						Title: null,
						Description: null,
						Label: null,
						Thumbnail: null,
						NoSend: true,
					};
					this.toSendInfo(this.infoTemplate);
					this.toBottom(100);
					socket.emit("sendToRobot", this.infoTemplate);
					// this.sendFailed(this.infoTemplate);
				} else {
					return null;
				}
			},
			//获取当前时间
			nowTime() {
				var myDate = new Date();
				//获取当前年
				var year = myDate.getFullYear();
				//获取当前月
				var month = myDate.getMonth() + 1;
				//获取当前日
				var date = myDate.getDate();
				var h = myDate.getHours(); //获取当前小时数(0-23)
				var m = myDate.getMinutes(); //获取当前分钟数(0-59)
				var s = myDate.getSeconds();
				var t = myDate.getMilliseconds();
				var now =
					year + "-" + month + "-" + date + " " + h + ":" + m + ":" + s + ":" + t;
				return now;
			},
			//发送消息模板
			toSendInfo(data) {
				/*
				 * identity:【0：机器人】【1：客服】 【2：顾客】
				 * type:【0:文本】 【1:图片】 【2:表情】 【3:商品卡片/订单卡片】
				 * */
				this.conversition.push({
					SendId: data.SendId,
					ReviceId: data.ReviceId,
					Content: data.Content,
					Identity: data.Identity,
					Type: data.Type,
					State: data.State,
					NoCode: data.NoCode,
					OutTradeNo: data.OutTradeNo,
					CreateDateUtc: data.CreateDate,
					Title: data.Title,
					Description: data.Description,
					Label: data.Label,
					Thumbnail: data.Thumbnail,
					noSend: true,
				});
				this.toBottom(100);
			},
			//打开更多功能
			openMore(type) {
				switch (type) {
					case "input":
						this.moreTool = false;
						this.expressionShow = false;
						this.changeHeight();
						this.toBottom(100);
						break;
					case "tool":
						this.expressionShow = false;
						this.moreTool = !this.moreTool;
						this.changeHeight();
						this.toBottom(100);
						break;
					case "expression":
						this.moreTool = false;
						this.expressionShow = !this.expressionShow;
						this.changeHeight();
						this.toBottom(100);
						break;
				}
			},
			//自适应高度
			changeHeight() {
				setTimeout(() => {
					this.getTelephoneInfo()
				}, 10)
			},
			//回到底部
			toBottom(time) {
				setTimeout(() => {
					this.scrollTop = 999991;
				}, time);
				setTimeout(() => {
					this.scrollTop = 999999;
					clearTimeout();
				}, time + 100);
			},
			//1.信息组装
			signalrService(
				content,
				identity,
				type,
				isSendOther = true,
				isRobot = false
			) {
				if (this.sendState) {
					let createDate = this.nowTime();
					let noCode = +new Date();
					this.infoTemplate = {
						SendId: this.sender.id,
						ReviceId: isRobot ? 0 : this.revicer.id,
						Content: content,
						Identity: identity,
						Type: type,
						State: isRobot || !this.sender.onlineState ? 1 : 0,
						NoCode: noCode,
						OutTradeNo: this.revicer.outTradeNo,
						CreateDateUtc: createDate,
						Title: null,
						Description: null,
						Label: null,
						Thumbnail: null,
						NoSend: true,
					};
					this.toSendInfo(this.infoTemplate);
					if (isSendOther) this.sendMsg(this.infoTemplate);
					this.sendState = isRobot || !this.sender.onlineState ? true : false;
					this.sendInfo = type == 2 ? this.sendInfo : "";
					this.toBottom(100);
				} else {
					Common.tipMsg("发送太快啦，请稍后再试");
				}
			},
			//2.发送信息
			sendMsg(data) {
				socket.emit("sendMsg", data);
				this.sendFailed(data);
			},
			//加载更多
			loadMore() {
				/*
				 * ##发起请求获取更多聊天记录
				 */
				Common.tipMsg("发起请求获取更多聊天记录");
			},
			//开启信息状态定时器
			sendFailed(msg) {
				this.msgTimer = setTimeout(() => {
					this.conversition.forEach((x) => {
						if (x.NoCode != null && x.NoCode == msg.NoCode) {
							x.State = -1;
						}
					});
					this.sendState = true;
				}, 20000);
			},
		},
		mounted() {
			this.getTelephoneInfo();
			that = this;
			this.init()
		}
	}
</script>
<style lang="scss">
	@import "../../static/css/chat.wxss";
</style>
